import re

from PyQt5.QtGui import QIcon, QPixmap, QFont
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QLabel, QLineEdit, QHBoxLayout, QMessageBox, QFrame, \
    QRadioButton
from PyQt5.QtCore import Qt
import requests
import threading
import time


class Register(QWidget):
    def __init__(self, parent=None):
        super().__init__()
        self.parent = parent
        self.sf='student'
        self.input_lis=[]
        self.setWindowTitle('用户注册')
        self.resize(500, 800)
        self.ver_code=False #验证码
        # 仅添加样式美化，不改变原有结构
        self.setStyleSheet("""
            QWidget {
                font-family: 'Microsoft YaHei', sans-serif;
                background-color: #f5f5f5;
            }
            QLabel {
                color: #333333;
                font-size: 14px;
            }
            QLineEdit {
                padding: 8px;
                border: 1px solid #cccccc;
                border-radius: 4px;
                background-color: white;
                font-size: 13px;
            }
            QLineEdit:focus {
                border-color: #66afe9;
                outline: none;
            }
            QPushButton {
                padding: 8px 12px;
                border-radius: 4px;
                border: none;
                background-color: #428bca;
                color: white;
                font-size: 13px;
            }
            QPushButton:hover {
                background-color: #3071a9;
            }
            QFrame {
                background-color: transparent;
            }
        """)

        try:
            icon = QIcon('../static/image/注册.png')
            self.setWindowIcon(icon)
        except:
            pass
        mainLayout = QVBoxLayout(self)
        self.initUI(mainLayout)

    def initUI(self, mainLayout):
        logo = QLabel()
        try:
            img = QPixmap('../static/image/注册.png')
            img = img.scaled(200, 200, Qt.KeepAspectRatio)
            logo.setPixmap(img)
        except:
            logo.setText("学籍管理注册")
            logo.setStyleSheet("font-size: 20px; color: #428bca; font-weight: bold;")

        logo.setAlignment(Qt.AlignCenter)
        mainLayout.addWidget(logo)

        text = QLabel('欢迎加入我们')
        text.setStyleSheet("font-size: 16px; margin: 10px 0;")
        text.setAlignment(Qt.AlignCenter)
        mainLayout.addWidget(text)

        frame = QFrame()
        mainLayout.addWidget(frame)
        layout1 = QVBoxLayout(frame)

        type_frame = QFrame()
        type_layout = QHBoxLayout(type_frame)
        type_label = QLabel('用户类型:')
        self.teacher_radio = QRadioButton('教师')
        self.student_radio = QRadioButton('学生')
        self.student_radio.setChecked(True)
        self.teacher_radio.toggled.connect(self.update_account_placeholder)
        type_layout.addWidget(type_label)
        type_layout.addWidget(self.teacher_radio)
        type_layout.addWidget(self.student_radio)
        layout1.addWidget(type_frame)

        self.get_v('账号', '请输入学号', layout1)
        self.get_v('姓名', '请输入姓名', layout1)
        self.get_v('邮箱', '请输入邮箱', layout1, 1)
        self.get_v('验证码', '请输入验证码', layout1)
        self.get_v('密码', '请输入密码', layout1, 2)
        self.get_v('确认密码', '请再次输入密码', layout1, 2)

        submit = QPushButton('确认')
        submit.setStyleSheet("background-color: #5cb85c; padding: 10px; font-size: 14px;")
        mainLayout.addWidget(submit)
        submit.clicked.connect(self.submit)

        exit = QPushButton('返回')
        exit.setStyleSheet("background-color: #d9534f; padding: 10px; font-size: 14px;")
        mainLayout.addWidget(exit)
        exit.clicked.connect(self.exit)


    def get_v(self, text1, text2, layout1, statu=None):
        frame = QFrame()
        layout1.addWidget(frame)
        layout2 = QHBoxLayout(frame)

        label = QLabel(text1)
        label.setFixedWidth(60)  # 固定宽度使对齐更整齐
        layout2.addWidget(label)

        input = QLineEdit()
        input.setPlaceholderText(text2)
        input.setMinimumHeight(32)  # 增加高度，提升体验
        layout2.addWidget(input)

        # 存储输入框引用用于类型切换
        if text1 == '账号':
            self.account_input = input

        # 保持原有按钮逻辑和位置
        if statu == 1:
            self.ver_send_submit = QPushButton('发送')
            layout2.addWidget(self.ver_send_submit)
            self.ver_send_submit.setFixedWidth(100)
            self.ver_send_submit.clicked.connect(self.send_ver)
        # 密码框设置
        if statu == 2:
            input.setEchoMode(QLineEdit.Password)
        self.input_lis.append(input)
    #发送验证码
    def send_ver(self):
        email=self.input_lis[2].text()
        email_exit=re.findall(r"^[0-9a-zA-Z]+@[a-zA-Z]{2,5}\.com$",email)
        if email_exit:
            par={'to_ad':email}
            response=requests.post('http://127.0.0.1:8000/users/email',params=par).json()
            self.ver_code=response.get('msg')
            self.input_lis[2].setEnabled(False)
            threading.Thread(target=self.time_ver_send).start()
        else:
            QMessageBox.critical(None, '错误', '邮箱格式错误')
            self.input_lis[2].clear()
    def update_account_placeholder(self):
        if hasattr(self, 'account_input'):
            if self.teacher_radio.isChecked():
                self.account_input.setPlaceholderText('请输入教师编号')
                self.sf='teacher'
            else:
                self.account_input.setPlaceholderText('请输入学号')
                self.sf='student'
    #注册
    def submit(self):
        sno=self.input_lis[0].text()
        name=self.input_lis[1].text()
        email=self.input_lis[2].text()
        ver_code=self.input_lis[3].text()
        password=self.input_lis[4].text()
        again_password=self.input_lis[5].text()
        if sno =='' or name=='' or email=='' or ver_code=='' or password=='' or again_password=='':
            QMessageBox.critical(None,'错误','请将信息填写完整')
            return
        else:
            if len(password) < 8 or len(password) > 32:
                QMessageBox.critical(None, '错误', '密码必须大于8位,小于32位')
                return
            if password != again_password:
                QMessageBox.critical(None,'错误','两次输入的密码不相同')
                return
            if self.ver_code != ver_code:
                QMessageBox.critical(None,'错误','验证码错误')
                return
            par={
                'name':name,
                'password':password,
                'sno':sno,
                'email':email,
            }
            response=requests.post('http://127.0.0.1:8000/users/student_register',json=par).json()
            if response.get('code') ==200:
                QMessageBox.information(None,'提示','注册成功')
            else:
                QMessageBox.critical(None, '错误', response['msg'])

    #返回
    def exit(self):
        if self.parent:
            self.parent.show()
        self.close()
    #验证码发送计数器
    def time_ver_send(self):
        for i in range(90):

            timer=90-i
            time.sleep(1)
            text=f'{str(timer)}后可重发'
            self.ver_send_submit.setText(text)
        self.setEnabled(True)

